﻿layui.use(['webuploader'], function () {
    var $ = layui.jquery, WebUploader = layui.webuploader;
    layui.link(layui.cache.base + 'uploader/uploader.css');

    var upLoadParam = [{"title":"图片上传","size":0,"filetypes":"jpg,png,gif,bmp","mimeTypes":".jpg,.png,.gif,.bmp"},{"title":"附件上传","size":0,"filetypes":"rar,zip,txt","mimeTypes":".rar,.zip,.txt"},{"title":"视频上传","size":0,"filetypes":"flv,mp3,mp4,avi","mimeTypes":".flv,.mp3,.mp4,.avi"}];

    //初始化绑定默认的属性
    $.upLoadDefaults = $.upLoadDefaults || {};
    $.upLoadDefaults.property = {
        multiple: false, //是否多文件
        water: false, //是否加水印
        thumbnail: false, //是否生成缩略图
        sendurl: null, //发送地址
        channel: 0,  //频道ID
        chunked: false,
        width: 0,  //强制宽度
        height: 0,   //强制高度
        cover: false,  //是否为封面
        compress: 1,  //是否开启后台检测，大最最大限制时，自动压缩 0否，1是（默认为开启）
        uptype: "img", //上传类型，img图片,file文件，video视频
        btntext: "上传...", //上传按钮的文字
        swf: null //SWF上传控件相对地址
    };

    //初始化上传控件
    $.fn.InitUploader = function (b) {
        var fun = function (parentObj) {
            var index = 0;
            var p = $.extend({}, $.upLoadDefaults.property, b || {});
            var btnObj = $('<div class="upload-btn">' + p.btntext + '</div>').appendTo(parentObj);
            var strpath = parentObj.siblings(".upload-path");
            if (p.type != 1 && p.type != 2 && !p.multiple) {
                if (strpath.val() != "") {
                    parentObj.parents("div.layui-input-block").append('<div class="layer-photos"><img src="' + strpath.val() + '"/></div>');
                } else {
                    parentObj.parents("div.layui-input-block").append('<div class="layer-photos hide"><img src="/images/nopic.png"/></div>');
                }
            }
            //初始化属性
            p.sendurl += "?action=UpLoadFile";
            if (p.water) {
                p.sendurl += "&IsWater=1";
            }
            if (p.thumbnail) {
                p.sendurl += "&IsThumbnail=1";
            }
            if (!p.multiple) {
                p.sendurl += "&DelFilePath=" + parentObj.siblings(".upload-path").val();
            }
            //频道
            if (p.channel > 0) {
                p.sendurl += "&channel=" + p.channel;
            }
            //强制宽高
            if (p.width > 0) {
                p.sendurl += "&width=" + p.width;
            }
            if (p.height > 0) {
                p.sendurl += "&height=" + p.height;
            }
            //是否标记为封面（频道专用）
            if (p.cover) {
                p.sendurl += "&cover=1";
            }
            //是否压缩
            p.sendurl += "&compress=" + p.compress;
            //上传类型
            if (p.type == undefined || p.type == "") {
                p.uptype = "img";
            } else if (p.type == 1) {
                index = 1;
                p.uptype = "file";
            } else if (p.type == 2) {
                index = 2;
                p.uptype = "video";
            } else {
                p.uptype = "img";
            }
            p.sendurl += "&uptype=" + p.uptype;
            var GUID = WebUploader.Base.guid(); //当前页面是生成的GUID作为标示

            //初始化WebUploader
            var uploader = WebUploader.create({
                compress: false, //不压缩
                auto: true, //自动上传
                chunked: p.chunked, //分片处理大文件
                chunkSize: 2 * 1024 * 1024,//由于Http的无状态特征，在往服务器发送数据过程传递一个进入当前页面是生成的GUID作为标示
                threads: 1, //上传并发数
                fileNumLimit: 300,
                //fileSizeLimit: 200 * 1024 * 1024,    // 200 M
                //fileSingleSizeLimit: 50 * 1024 * 1024 ,   // 50 M
                swf: p.swf, //SWF路径
                server: p.sendurl, //上传地址
                pick: {
                    id: btnObj,
                    multiple: p.multiple
                },
                accept: {
                    title: upLoadParam[index].title,
                    extensions: upLoadParam[index].filetypes,
                    mimeTypes: upLoadParam[index].mimeTypes
                },
                formData: {
                    DelFilePath: '', //定义参数
                    guid: GUID,
                    ischunk: p.chunked
                },
                fileVal: 'Filedata', //上传域的名称
                sendAsBinary: true, //二进制流上传
                fileSingleSizeLimit: upLoadParam[index].size * 1024 //文件大小
            });

            // 拖拽时不接受 js, txt 文件。
            uploader.on('dndAccept', function (items) {
                var denied = false,
                    len = items.length,
                    i = 0,
                // 修改js类型
                    unAllowed = 'text/plain;application/javascript ';
                for (; i < len; i++) {
                    // 如果在列表里面
                    if (~unAllowed.indexOf(items[i].type)) {
                        denied = true;
                        break;
                    }
                }
                return !denied;
            });

            //当validate不通过时，会以派送错误事件的形式通知
            uploader.on('error', function (type) {
                switch (type) {
                    case 'Q_EXCEED_NUM_LIMIT':
                        layer.alert("错误：上传文件数量过多！");
                        break;
                    case 'Q_EXCEED_SIZE_LIMIT':
                        layer.alert("错误：文件总大小超出限制！");
                        break;
                    case 'F_EXCEED_SIZE':
                        layer.alert("错误：文件大小超出限制！");
                        break;
                    case 'Q_TYPE_DENIED':
                        layer.alert("错误：禁止上传该类型文件！");
                        break;
                    case 'F_DUPLICATE':
                        layer.alert("错误：请勿重复上传该文件！");
                        break;
                    default:
                        layer.alert('错误代码：' + type);
                        break;
                }
            });

            //当有文件添加进来的时候
            uploader.on('fileQueued', function (file) {
                //如果是单文件上传，把旧的文件地址传过去
                if (!p.multiple) {
                    uploader.options.formData.DelFilePath = parentObj.siblings(".upload-path").val();
                }
                //防止重复创建
                if (parentObj.children(".upload-progress").length == 0) {
                    //创建进度条
                    var fileProgressObj = $('<div class="upload-progress"></div>').appendTo(parentObj);
                    var progressText = $('<span class="txt">正在上传，请稍候...</span>').appendTo(fileProgressObj);
                    var progressBar = $('<span class="bar"><b></b></span>').appendTo(fileProgressObj);
                    var progressCancel = $('<a class="close" title="取消上传"><i class="iconfont icon-remove"></i></a>').appendTo(fileProgressObj);
                    //绑定点击事件
                    progressCancel.click(function () {
                        uploader.cancelFile(file);
                        fileProgressObj.remove();
                    });
                }
            });

            //文件上传过程中创建进度条实时显示
            uploader.on('uploadProgress', function (file, percentage) {
                var progressObj = parentObj.children(".upload-progress");
                progressObj.children(".txt").html(file.name);
                progressObj.find(".bar b").width(percentage * 100 + "%");
            });

            //当文件上传出错时触发
            uploader.on('uploadError', function (file, reason) {
                uploader.removeFile(file); //从队列中移除
                layer.alert(file.name + "上传失败，错误代码：" + reason);
            });

            //当文件上传成功时触发
            uploader.on('uploadSuccess', function (file, data) {
                if (p.chunked) {
                    if (data.chunked) {
                        var index = layer.msg('正在合并文件', { icon: 16, time: 0, shade: 0.01 });
                        $.ajax({
                            url: "/upload_ajax/mergefiles",
                            type: "post",
                            dataType: "json",
                            data: { guid: GUID, fileExt: data.f_ext, path: data.path },
                            success: function (res) {
                                if (res.status == '0') {
                                    layer.alert('文件合并失败！');
                                    layer.close(index);
                                } else {
                                    //如果是单文件上传，则赋值相应的表单
                                    if (!p.multiple) {
                                        parentObj.siblings(".upload-name").val(data.name);
                                        parentObj.siblings(".upload-path").val(res.path);
                                        parentObj.siblings(".upload-size").val(res.size);
                                        var showImg = parentObj.nextAll(".layer-photos").show().find("img");
                                        if (showImg.length > 0) {
                                            showImg.attr("src", res.path);
                                        }
                                    } else {
                                        addImage(parentObj, res.path, res.thumb);
                                    }
                                    layer.msg('合并成功！');
                                    layer.close(index);
                                }
                            }
                        });
                    }
                } else {
                    if (data.status == '0') {
                        var progressObj = parentObj.children(".upload-progress");
                        progressObj.children(".txt").html(data.msg);
                    }
                    if (data.status == '1') {
                        //如果是单文件上传，则赋值相应的表单
                        if (!p.multiple) {
                            parentObj.siblings(".upload-name").val(data.name);
                            parentObj.siblings(".upload-path").val(data.path);
                            parentObj.siblings(".upload-size").val(data.size);
                            var showImg = parentObj.nextAll(".layer-photos").show().find("img");
                            if (showImg.length > 0) {
                                showImg.attr("src", data.path);
                            }
                        } else {
                            addImage(parentObj, data.path, data.thumb);
                        }
                        var progressObj = parentObj.children(".upload-progress");
                        progressObj.children(".txt").html("上传成功：" + file.name);
                    }
                }
                uploader.removeFile(file); //从队列中移除
            });

            //不管成功或者失败，文件上传完成时触发
            uploader.on('uploadComplete', function (file) {
                var progressObj = parentObj.children(".upload-progress");
                progressObj.children(".txt").html("上传完成");
                //如果队列为空，则移除进度条
                if (uploader.getStats().queueNum == 0) {
                    progressObj.remove();
                }
            });
        };
        return $(this).each(function () {
            fun($(this));
        });
    }
});
//添加图片相册
function addImage(targetObj, originalSrc, thumbSrc) {
    //插入到相册UL里面
    var newLi = $('<div class="photo-li">'
        + '<input type="hidden" name="hid_photo_name" value="0|' + originalSrc + '|' + thumbSrc + '" />'
        + '<input type="hidden" name="hid_photo_remark" value="" />'
        + '<input type="hidden" name="hid_photo_sort" class="hid_photo_sort" value="99" />'
        + '<div class="img-box" onclick="setFocusImg(this);">'
        + '<img src="' + thumbSrc + '" bigsrc="' + originalSrc + '" />'
        + '<span class="remark"><i>暂无描述...</i></span>'
        + '</div>'
        + '<a href="javascript:;" onclick="setRemark(this);">描述</a>'
        + '<a href="javascript:;" onclick="delImg(this);">删除</a>'
        + '<a href="javascript:;" class="viewImg" onclick="ajaxLoadImg(0);">浏览</a>'
        + '<a href="javascript:;" onclick="onOrder(this, -1);" class="pre" title="前移"><i class="layui-icon layui-icon-prev"></i></a><a href="javascript:;" onclick="onOrder(this, 1);" class="next" title="后移"><i class="layui-icon layui-icon-next"></i></a>'
        + '</div>');
    newLi.appendTo(targetObj.siblings(".photo-list").children(".photo-ul"));

    //默认第一个为相册封面
    var focusPhotoObj = targetObj.siblings(".focus-photo");
    if (focusPhotoObj.val() == "") {
        focusPhotoObj.val(thumbSrc);
        newLi.children(".img-box").addClass("selected");
    }
}
//弹出显示图片
function ajaxLoadImg(i) {
    var data = [];
    $(".photo-list").find(".photo-li").each(function (index) {
        var src = $(this).find("img").attr("bigsrc"), title = $(this).find(".remark").text();
        data.push({ "alt": title, "pid": index, "src": src, "thumb": "" });
    });
    var json = {
        "title": "图片相册", //相册标题
        "id": 1, //相册id
        "start": i, //初始显示的图片序号，默认0
        "data": data
    };
    layer.photos({
        photos: json,
        anim: 5
    });
}
//排序
function onOrder(o, t) {
    if (t > 0) {
        //后移
        $(o).parent(".photo-li").next(".photo-li").insertBefore($(o).parent(".photo-li"));
    } else {
        //前移
        $(o).parent(".photo-li").prev(".photo-li").insertAfter($(o).parent(".photo-li"));
    }
    //重新分配排序
    $(o).parent().parent().find(".photo-li").each(function (index) {
        $(this).find(".hid_photo_sort").val(index);
    });
}
//设置相册封面
function setFocusImg(obj) {
    var focusPhotoObj = $(obj).parents(".photo-list").siblings(".focus-photo");
    focusPhotoObj.val($(obj).children("img").eq(0).attr("src"));
    $(obj).parent().siblings().children(".img-box").removeClass("selected");
    $(obj).addClass("selected");
}
//设置图片描述
function setRemark(obj) {
    var parentObj = $(obj); //父对象
    var hidRemarkObj = parentObj.prevAll("input[name='hid_photo_remark']").eq(0); //取得隐藏值
    top.layer.prompt({
        formType: 2,
        title: '图片描述',
        value: hidRemarkObj.val(),
        btn: ['批量描述', '单张描述', '取消'],
        btn2: function (index, elem) {
            var value = top.layui.jquery('#layui-layer' + index + " .layui-layer-input").val();
            if (value == "") {
                parent.layer.alert('亲，总该写点什么吧？', { closeBtn: 0 }, function (index) { parent.layer.close(index); });
                return false;
            }
            hidRemarkObj.val(value);
            parentObj.siblings(".img-box").children(".remark").children("i").html(value);
            top.layer.close(index);
        }
    }, function (value, index, elem) {
        parentObj.parent().parent().find(".photo-li input[name='hid_photo_remark']").val(value);
        parentObj.parent().parent().find(".photo-li .img-box .remark i").html(value);
        top.layer.close(index);
    });
}
//删除图片LI节点
function delImg(obj) {
    var parentObj = $(obj).parent().parent();
    var focusPhotoObj = parentObj.parent().siblings(".focus-photo");
    var smallImg = $(obj).siblings(".img-box").children("img").attr("src");
    $(obj).parent().remove(); //删除的LI节点
    //检查是否为封面
    if (focusPhotoObj.val() == smallImg) {
        focusPhotoObj.val("");
        var firtImgBox = parentObj.find(".photo-li .img-box").eq(0); //取第一张做为封面
        firtImgBox.addClass("selected");
        focusPhotoObj.val(firtImgBox.children("img").attr("src")); //重新给封面的隐藏域赋值
    }
}